package com.intellif.mozping.threadcooperation.pool;

import java.sql.Connection;
import java.util.LinkedList;

/**
 * @author by mozping
 * @Classname MyDbPool
 * @Description TODO
 * @Date 2018/12/28 19:43
 */
public class MyDbPool {

    private static LinkedList<Connection> pool = new LinkedList<>();

    public MyDbPool(int initalSize) {
        if (initalSize <= 0) {
            initalSize = 1;
        }
        for (int i = 0; i < initalSize; i++) {
            pool.addLast(MyConnection.fetchConnection());
        }
    }

    public Connection featchConnection(long mills) throws InterruptedException {
        synchronized (pool) {
            if (mills < 0) {
                while (pool.isEmpty()) {
                    pool.wait();
                }
                return pool.removeFirst();
            } else {
                long overtime = System.currentTimeMillis() + mills;
                long remain = mills;
                while (pool.isEmpty() && remain > 0) {
                    pool.wait(remain);
                    remain = overtime - System.currentTimeMillis();
                }
                Connection result = null;
                if (!pool.isEmpty()) {
                    result = pool.removeFirst();
                }
                return result;
            }
        }
    }

    public void releaseConnection(Connection conn) {
        if (conn != null) {
            synchronized (pool) {
                pool.addLast(conn);
                pool.notifyAll();
            }
        }
    }
}
